package com.vast.vastlcd.connection;

import org.eclipse.jface.action.Action;


public class ConnectionManager implements Runnable {
	
	
	private Action startAction;
	private Action stopAction;
	
	private ConnectionManager instance;
	private IConnection connection = null;
	
	public ConnectionManager() {
		instance = this;
		startAction = new Action() {
			public void run() {
				startClient();
			}
		};
		startAction.setEnabled(false);
		
		
		startAction.setToolTipText("Connect");

		stopAction = new Action() {
			public void run() {
				stopClient();
			}
		};

		stopAction.setToolTipText("Stop connection");
		stopAction.setEnabled(false);
	}
	
	public ConnectionManager(IConnection connection) {
		instance = this;
		this.connection = connection;
		startAction = new Action() {
			public void run() {
				if (startClient()) {
					new Thread(instance).start(); // Task 1 (Pure Java Task) : data acqusition
				}
			}
		};
		
		startAction.setToolTipText("Connect");

		stopAction = new Action() {
			public void run() {
				stopClient();
			}
		};

		stopAction.setToolTipText("Stop connection");
		stopAction.setEnabled(false);
	}
	
	public enum State {
		IDLE, CONNECT, INIT, RUNNING
	}
	
	private State running = State.IDLE;
	
	public boolean startClient() {
		if (running == State.IDLE) {
			this.running = State.CONNECT;
			stopAction.setEnabled(true);
			startAction.setEnabled(false);
			new Thread(instance).start(); // Task 1 (Pure Java Task) : data acqusition
			return true;
		} else {
			System.out.println("Server is already running...");
			return false;
		}
	}

	public void stopClient() {
		this.running = State.IDLE;
		stopAction.setEnabled(false);
		startAction.setEnabled(true);
	}
	
	public boolean isRunning() {
		return running != State.IDLE;
	}

	public synchronized void run() {
		if (connection == null)
			return;
		try {
			while(running!= State.IDLE){
				if (running == State.CONNECT) {
					if (connection.connect()) {
						running = State.INIT;
					} else {
						wait(500);
					}
				} else if (running == State.INIT) { 
					if (!connection.initialize()) {
						stopClient();
						return;
					}
					running = State.RUNNING;
				} else if (running == State.RUNNING) {
					if (!connection.synchonize()) {
						stopClient();
						return;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public Action getStartAction() {
		return startAction;
	}


	public Action getStopAction() {
		return stopAction;
	}

	public void setConnection(IConnection connection) {
		if (this.connection != null) {
			stopClient();
		}
		
		this.connection = connection;
		if (this.connection != null) {
			startAction.setEnabled(true);
			stopAction.setEnabled(false);
		}
		
	}
	
}
